package com.jt.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jt.mapper.StaffMapper;
import com.jt.pojo.Staff;
import com.jt.vo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class StaffServiceImpl implements StaffService{
    @Autowired
    private StaffMapper staffMapper;


    @Override
    public List<Staff> findAll() {
        return staffMapper.selectList(null);
    }


    /**
     *关于分页查询的说明
     */
    @Override
    public PageResult getStaffList(PageResult pageResult) {
        IPage page = new Page(pageResult.getPageNum(),pageResult.getPageSize());
        QueryWrapper<Staff> queryWrapper = new QueryWrapper<>();
        boolean flag = StringUtils.hasLength(pageResult.getQuery());
        queryWrapper.like(flag,"username", pageResult.getQuery())
                .or().like(flag,"id", pageResult.getQuery())
                .or().like(flag,"phone", pageResult.getQuery())
                .or().like(flag,"email", pageResult.getQuery())
                .or().like(flag,"job", pageResult.getQuery())
                .or().like(flag,"department", pageResult.getQuery());
        page = staffMapper.selectPage(page,queryWrapper);
        long total = page.getTotal();//总数
        List<Staff> list = page.getRecords();//MP帮助实现了分页查询结果
        return pageResult.setRows(list).setTotal(total);
    }

    /**
     * 状态更新
     * @param staff
     */
    @Override
    @Transactional
    public void updateStatus(Staff staff) {
        staffMapper.updateById(staff);
    }

    /**
     * 根据ID删除
     * @param id
     */
    @Override
    @Transactional
    public void deleteStaffById(Integer id) {
        staffMapper.deleteById(id);
    }

    /**新增
     */
    @Override
    @Transactional //事务控制
    public void addStaff(Staff staff) {
        staff.setStatus(true);//设定状态默认值
        staffMapper.insert(staff);

    }
    /**
     * 根据ID查询数据库
     */
    @Override
    public Staff getStaffById(Integer id) {
        return staffMapper.selectById(id);
    }

    @Override
    @Transactional
    public void updateStaff(Staff staff) {
        staffMapper.updateById(staff);
    }
}